
from flask import Blueprint, render_template, redirect,jsonify,url_for,session
from exts import mail,db
from flask_mail import Message
from flask import request
import string
import random
from models import EmailCaptchaModel,UserModel
import threading
from functools import wraps
from .forms import RegisterForm, LoginForm
#用于密码加密
from werkzeug.security import generate_password_hash,check_password_hash

#在此蓝图中用bp创建视图函数
bp = Blueprint("auth",__name__,url_prefix="/auth")


#如果不指定methods方法，默认get请求
#bp.route('/',methods=['POST'])
@bp.route("/login",methods=["GET","POST"])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("该邮箱未注册")
                return redirect(url_for('auth.login'))
            if check_password_hash(user.password,password):
                #session经过加密存储在cookie中，需要在config中配置加密盐
                session['user_id'] = user.id
                return redirect('/')
            else:
                print("密码错误")
                return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))


@bp.route("/register",methods=["GET","POST"])
def register():
    if request.method == "GET":
         return render_template("register.html")
    else:
         form = RegisterForm(request.form)
         if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            #密码不能写成password = password ，安全起见要加密
            user = UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            #url_for自动将视图函数转为url
            return redirect(url_for('auth.login'))
         else:
            print(form.errors)
            return redirect(url_for('auth.register'))


@bp.route('/mail/test')
def mail_test():
    message = Message("email——test",recipients=["8210222402@csu.edu.cn"],body="这是一条测试邮件")
    mail.send(message)
    return "email send successfully"

#装饰器
def send_email_async_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 获取email
        email = request.args.get("email")

        # 生成验证码
        source = string.digits * 4
        captcha = ''.join(random.sample(source, 4))

        # 创建并发送邮件
        message = Message("YigongOA验证码", recipients=[email], body=f"您的验证码是：{captcha}")
        mail.send(message)
        email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
        db.session.add(email_captcha)
        db.session.commit()

        # 返回响应
        return jsonify({"code": 200, "message": "", "data": None})

    return wrapper

@bp.route('/logout')
def logout():
    session.clear()
    return redirect('/')

@bp.route("/captcha/email")
@send_email_async_decorator
def get_mail_captcha_code():
    return jsonify({"code":200,"message":"","data":None})
'''
def get_mail_captcha_code():
    email = request.args.get("email")
    #digits='0123456789'
    source = string.digits*4
    #随机从0123456789012345678901234567890123456789中取四位
    captcha = random.sample(source,4)
    #将列表转为字符串
    captcha = ''.join(captcha)
    #一般像这种耗时任务交给任务队列
    message = Message("YigongOA验证码", recipients=[email], body=f"您的验证码是：{captcha}")
    #存储验证码的三种方式：mecmcached缓存/redis硬盘/数据库   推荐存到内存（缓存）读取快
    email_captcha = EmailCaptchaModel(email = email, captcha = captcha)
    db.session.add(email_captcha)
    db.session.commit()'''
    #code:200/400/500